package qimao.com.edu.servlet;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import qimao.com.edu.DTO.ChapterDTO;
import qimao.com.edu.entity.Author;
import qimao.com.edu.entity.CommenResult;
import qimao.com.edu.entity.Page;
import qimao.com.edu.service.AuthorService;
import qimao.com.edu.service.impl.AuthorServiceImpl;
import qimao.com.edu.util.CookieUtils;

@WebServlet("/writer/loginWriter.do")
public class LoginWriterServlet extends HttpServlet {

    AuthorService as = new AuthorServiceImpl();
    Author author=new Author();
   

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	
    	// 设置请求和响应的字符编码，防止中文乱码
    	HttpSession session = req.getSession(true);
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        // 获取表单参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
//        System.out.println(username+"-------"+password);
        author.setUsername(username);
        author.setPassword(password);
//        boolean rememberMe = "true".equals(req.getParameter("rememberMe"));
        
         //验证用户
        Map<String, Object> map=as.authorLogin(author);
        
        System.out.println(map);
        System.out.println(map.get("loginAuthor"));
        if(map.get("loginAuthor") != null) {
//        	 resp.sendRedirect("index.html");
        	 session.setAttribute("loginAuthor", map.get("loginAuthor"));
        	 session.setMaxInactiveInterval(30 * 30 * 60);
        	 req.getRequestDispatcher("index.html").forward(req, resp);

        }else {
        	Cookie errorCookie = new Cookie("loginError", URLEncoder.encode("认证失败或权限不足", "UTF-8"));
        	errorCookie.setPath("/");
        	errorCookie.setMaxAge(30); // 30秒有效期
        	resp.addCookie(errorCookie);
        	resp.sendRedirect("login-writer.html");
//        	req.getRequestDispatcher("login-writer.html").forward(req, resp);
        }
        
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}